package com.apes.scm.masterdata.finance.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.finance.model.PosBind;
import com.apes.scm.masterdata.finance.repository.PosBindRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：
 *
 * @Auther: wuq
 * @Date: 2018-08-14 10:20
 */
@Service("posBindService")
public class PosBindService extends DomainService {

    @Autowired
    PosBindRepository posBindRepository;

    /**
     * 保存
     * @param request
     * @return
     */
    public PosBind save(SimpleRequest request){
        PosBind posBind = request.getO(PosBind.class);
        return posBindRepository.saveAndFlush(posBind);
    }

    public PosBind update(SimpleRequest request) {
        String id = request.get("id");
        int version = request.get("version");

        // 从数据库中取数，检查数据
        PosBind oldPosBind = posBindRepository.findOne(id);
        if (oldPosBind == null) throw new RuntimeException("会员级别【" + id + "】在系统中不存在。");
        if (oldPosBind.getVersion() != version) throw new RuntimeException("记录已更新或已删除，请重新提交！");

        PosBind vipLevel = request.getO(PosBind.class);
        return posBindRepository.saveAndFlush(vipLevel);
    }

    /**
     * 查询
     * @param request
     * @return
     */
    public Page<PosBind> findAll(SimpleRequest request){
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return posBindRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }
}
